package org.yxk.login.controller;

import java.util.UUID;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.resource.HttpResource;
import org.yxk.login.pojo.User;
import org.yxk.login.utils.LoginCache;

@Controller
public class LoginController {
	
	@GetMapping("/view/login")
	public String toLogin(@RequestParam(required=false,defaultValue="") String target,HttpSession session,HttpResource resource) {
		if(StringUtils.isEmpty(target)) {
			target="http://www.yxk.com:9010";
		}
		//重定向地址
		session.setAttribute("target", target);
		return "/login";
	}
	@RequestMapping("/login")
	public String login(User u,HttpSession session) {
		if(!"admin".equals(u.getUsername())) {//模拟校验用户
			session.setAttribute("msg", "用户名或者密码错误");
			return "login";
		}
		String token= UUID.randomUUID().toString();
		Cookie c = new Cookie("token", token);
		
		LoginCache.Users.put(token, u);
		String target=(String) session.getAttribute("target");
		//重定向到target地址
		return "redirect:"+target;
	}
}
